import { Message } from 'element-ui'
import localStorageService from '../ddd/localStorage.service'
import { _dataEncryption } from './encryption.service.js'

export default function ({ $axios, redirect }) {
  $axios.defaults.baseURL = '/api/'

  $axios.defaults.timeout = 10000

  $axios.setHeader('Content-Type', 'application/json')

  $axios.onRequest(config => {
    const model = config.data || {}

    const signModel = _dataEncryption(model)

    if (['post', 'put', 'patch'].includes(config.method)) {
      config.data = signModel
    }

    if (['get', 'delete', 'head'].includes(config.method)) {
      const queryParams = Object.keys(signModel).map(m => { return `${m}=${signModel[m]}` }).join('&')

      config.url = `${config.url}?${queryParams}`
    }

    const token = localStorageService.getItem('access_token')

    if (token) {
      config.headers['authorization'] = `Bearer ${token}`
    }

    return config;
  })

  $axios.onResponse(response => {
    if (response.status == 200) {
      if (response.data.code == 200) {
        return Promise.resolve(response.data)
      } else {
        if (response.data.code == 401) {
          Message.error(response.data.msg)

          localStorageService.clear()

          setTimeout(() => {
            redirect('/')
          }, 1000)

          return Promise.reject(response)
        } else {
          console.log(response, '---')
          Message.error(response.data.msg)

          return Promise.reject(response)
        }
      }
    } else {
      Message.error('系统异常,请联系管理员')

      return Promise.reject(response)
    }
  })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)

    if (code === NaN) {
      return
    }

    switch (code) {
      case 405:
        Message.error('系统异常,请联系管理员')
        break
      case 400:
        redirect('/error')
        break
      case 500:
        Message.error('系统异常,请联系管理员')
        break
      case 502:
        Message.error('请求超时,请联系管理员')
        break
    }
  })
}